<template>
  <div id="companyAccountSetting" class="route-page">
    <a-card title="收支账户配置" class="card-with-title-page" size="small">
      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="dataList"
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @change="handleTableChange"
      >
        <template #title>
          <div class="flex justify-between header-clue">
            <div class="flex-1">
              <a-form layout="vertical">
                <a-row :gutter="8">
                  <a-col :span="3">
                    <a-form-item>
                      <a-input
                        placeHolder="请输入条目名称"
                        v-model:value="searchParams.name"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="3">
                    <a-form-item>
                      <a-input
                        placeHolder="请输入银行账户"
                        v-model:value="searchParams.bank"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="3">
                    <a-form-item>
                      <a-select
                        style="width: 100%"
                        :allowClear="true"
                        placeholder="请选择收款公司"
                        v-model:value="searchParams.org_branch_id"
                        :options="branchCompanyOptions"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="3">
                    <a-form-item>
                      <a-select
                        style="width: 100%"
                        :allowClear="true"
                        placeholder="请选择状态"
                        v-model:value="searchParams.status"
                        :options="statusOptions"
                      />
                    </a-form-item>
                  </a-col>

                  <a-col :span="3">
                    <a-form-item label="">
                      <a-space>
                        <a-button @click="reset">重置</a-button>
                        <a-button type="primary" @click="getTableData(true)">
                          搜索
                        </a-button>
                      </a-space>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <div>
              <a-space>
                <a-button type="primary" ghost @click.stop="handleExport">导出</a-button>
                <a-button
                  v-permission="['manageAccount', 'curd', 'add']"
                  type="primary"
                  @click="editAccount()"
                >新增收支账户</a-button
                >
              </a-space>
            </div>
          </div>
        </template>
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'status'">
            <a-switch
              v-permission="['manageAccount', 'curd', 'status']"
              :checkedValue="1"
              :unCheckedValue="0"
              :checked="text"
              checked-children="开启"
              un-checked-children="关闭"
              @click="(checked) => handleStatusClick(record.id, checked)"
            />
          </template>
          <template v-if="column.key === 'name'">
            <span>{{text}}</span>
            <a-tag color="blue" style="margin-left: 4px" v-if="record.company">需编辑</a-tag>
          </template>
          <template v-if="column.key === 'is_company'">
            <span v-if="text == 1">公司</span>
            <span v-if="text == 0">个人</span>
          </template>
          <template v-if="column.key === 'action'">
            <a-button
              type="link"
              v-permission="['manageAccount', 'curd', 'edit']"
              @click="editAccount(text)"
              >编辑</a-button
            >
            <a-button
              type="link"
              v-permission="['manageAccount', 'curd', 'delete']"
              danger
              @click="deleteAccount(text)"
              >删除</a-button
            >
          </template>
        </template>
      </a-table>
    </a-card>
    <account-add
      @cancel="editAccountClose"
      @success="editSuccess"
      :visible="editVisible"
      :id="currentId"
      @request="$utils.commonRequest"
    ></account-add>
  </div>
</template>

<script>
import AccountAdd from "./modules/AccountAdd.vue";
import {computed, defineComponent, onActivated, reactive, ref, toRefs, watch} from "vue";
import {Form, message} from "ant-design-vue";
import utils from "../../../common/utils/utils";
const useForm = Form.useForm;
import request from "@/common/utils/request";
export default defineComponent({
  name: "manageAccount",
  components: { AccountAdd },
  setup() {
    /**
     * @description: 分页信息
     */
    const page = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: pageSize.value,
      showSizeChanger: true,
    }));

    const searchParams = reactive({
      name: "",
      bank: "",
      org_branch_id: undefined,
      status: undefined,
    });
    const { resetFields } = useForm(searchParams, {});

    const state = reactive({
      branchCompanyOptions: [],
      selectedRowKeys: [],
      statusOptions: [
        {
          label: '全部',
          value: 2,
        },
        {
          label: '正常',
          value: 1,
        },
        {
          label: '禁用',
          value: 0,
        },
      ],
    });

    const onSelectedRowChange = (selectedRowKeys) => {
      state.selectedRowKeys = selectedRowKeys;
    };

    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectedRowChange,
    }));

    /**
     * @description: 表格数据
     */
    const loading = ref(false);
    const dataList = ref([]);
    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      pageSize.value = pager.pageSize;
      getTableData();
    };

    /**
     * @description: 新增编辑表单
     */
    const editVisible = ref(false);
    const currentId = ref(0);

    const editAccount = (id) => {
      currentId.value = id || 0;
      editVisible.value = true;
    };

    const editAccountClose = () => {
      editVisible.value = false;
    };

    const editSuccess = () => {
      editAccountClose();
      getTableData();
    };

    const getCompany = () => {
      request.get("/org", "/company/orgAndBranch",)
        .then((res) => {
          state.branchCompanyOptions = (res?.list || []).map((item) => {
            return {
              value: item.id,
              label: item.company,
            }
          });
        })
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      getCompany();
      getTableData(true);
    };

    /**
     * @description: 获取表格数据
     */
    const getTableData = (init = false) => {
      loading.value = true;
      if (init) {
        page.value = 1;
        state.selectedRowKeys = [];
      }
      const params = {
        page: page.value,
        pageSize: pageSize.value,
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }
      request.get("/org", "/manage/account", params)
        .then((res) => {
          dataList.value = res.list;
          total.value = Number(res.total);
        })
        .finally(() => {
          loading.value = false;
        });
    };

    /**
     * @description: 编辑账户状态
     * @param {Number} id
     * @param {Number} checked 开启/关闭
     */
    const handleStatusClick = (id, checked) => {
      request.put("/org", "/manage/account/status", {
        id,
        status: checked,
      }).then((res) => {
        message.success(res.msg || "修改成功");
        getTableData();
      });
    };

    /**
     * @description: 删除账户配置
     * @param {Number} id
     */
    const deleteAccount = (id) => {
      utils.modalConfirm({
        content: "确认要删除当前账户配置吗？",
        okType: "danger",
        centered: true,
        onOk: () => {
          request.del("/org", "/manage/account", { id, needMsg: true }).then((res) => {
            message.success(res.msg || "删除成功");
            getTableData();
          });
        },
      });
    };

    const reset = () => {
      resetFields();
      getTableData(true);
    };

    // 导出报表
    let timer = null;
    const iframe = document.createElement("iframe");
    const handleExport = () => {
      if (timer) {
        message.warn("操作过于频繁，请稍后尝试");
        return;
      }
      let params = {
        ids: state.selectedRowKeys.join(','),
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }
      request
        .post("/org", "/account/exportAccount", params)
        .then((res) => {
          iframe.src = res.result.fileUrl;
          iframe.style.display = "none";
          document.body.appendChild(iframe);
          setTimeout(() => {
            document.body.removeChild(iframe);
          }, 1000);
          message.success("导出成功,请等待文件生成");
          timer = setTimeout(() => {
            timer = null;
          }, 20000);
        });
    };

    onActivated(() => {
      init();
    });

    return {
      ...toRefs(state),
      columns,
      dataList,
      editVisible,
      currentId,
      searchParams,
      rowSelection,
      loading,
      pagination,
      editAccount,
      editAccountClose,
      editSuccess,
      handleTableChange,
      handleStatusClick,
      deleteAccount,
      handleExport,
      getTableData,
      reset,
    };
  },
});

const columns = [
  {
    title: "条目名称",
    dataIndex: "name",
    key: "name",
    width: "16%",
  },
  {
    title: "收款公司",
    dataIndex: "company",
    key: "company",
    width: "15%",
    customRender: ({ text, record, index }) => {
      return record?.company ? record?.company : record?.new_company_name || '--';
    },
  },
  {
    title: "账户类型",
    dataIndex: "is_company",
    key: "is_company",
    width: "9%",
  },
  {
    title: "开户银行",
    dataIndex: "bank",
    key: "bank",
    width: "15%",
  },
  {
    title: "银行账号",
    dataIndex: "bank_account",
    key: "bank_account",
    width: "15%",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: "15%",
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
    width: "15%",
  },
];
</script>

<style lang="less" scoped>
.route-page .card-with-title-page {
  padding: 0 0 7px 0;
}
:deep(.ant-card-small > .ant-card-head) {
  height: 49px;
  min-height: initial;
}
:deep(.ant-card-head-wrapper) {
  height: 100%;
}
:deep(.ant-table-title) {
  padding: 6px 0;
}
</style>
